<template lang="pug">
    .list_main_box.font
        navs
        .boxs.m-auto.page-w
            .banner-box 榜单发布
            .map-box.m-t30.m-lr60
                .l-map
                    .l
                        div(ref="myEcharts", style="width: 100%; height: 100%")
                        .descr 参评机构数量
                    //- img(src="./../images/map.png")
                .custom.p-t30
                    .particulars
                        b 自定义检索
                        .input-box
                            span 年度
                            .select-box
                                el-select(v-model="form.year" placeholder="请选择" size='small')
                                    el-option(
                                        v-for="item in result.year"
                                        :key="item.val"
                                        :label="item.name"
                                        :value="item.val")
                                    
                            span 省市
                            .select-box
                                el-select(v-model="form.province" placeholder="请选择" size='small' clearable)
                                    el-option(
                                        v-for="item in result.province"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id")
                            span 医院名称
                            .select-box
                                el-select(v-model="form.organId" placeholder="请选择" size='small' clearable)
                                    el-option(
                                        v-for="item in filteredHospitals"
                                        :key="item.id"
                                        :label="item.organName"
                                        :value="item.id")
                            ul.filtration
                                li
                                    .custom-btn(@click="reset()") 重置
                                li
                                    .custom-btn(@click="retrieve()") 检索
            
            div.p-t40.m-lr60(style="background: #f6fefd;")
                ul.tabs
                    li(v-for="n in tabList" :key='n.val' :class="{on: currObj.onSeniority === n.val}" @click="tabListFn(n.val)") {{n.name}}
                
                table.table-version-list.green-table-theme.m-b100(cellspacing="0" v-loading='loading.tableLoading')
                    colgroup
                            col(span='1', v-for="(head, index) in tabHeads[currObj.onSeniority].heads" :key="index" :span="1" :width="getColumnWidth(index)")
                    thead
                        tr
                            th(v-for="(title, index) in tabHeads[currObj.onSeniority].heads") {{title}}
                    tbody(v-if='result.generalObj[currObj.onSeniority] && Object.keys(result.generalObj[currObj.onSeniority].organs).length === 0')
                        tr
                            td(:colspan='tabHeads[currObj.onSeniority].heads.length' style="text-align:center")
                                | 暂无数据
                    tbody(v-else)
                        template(v-if="result.generalObj[currObj.onSeniority]")
                            tr(v-for="(obj, index) in result.generalObj[currObj.onSeniority].organs") 
                                td(v-for="(key, i) in tabHeads[currObj.onSeniority].heads" :key='i')
                                    template(v-if="i===0")
                                        | 
                                        span(style="color:#111") {{index+1}}
                                    template(v-if="key==='机构名称'")
                                        | {{obj['organName']}}
                                    template(v-else)
                                        | {{obj.detailMap[key]}}
                                    

        .el-pagination-page.m-auto(v-if="false")
            el-pagination(background @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="pageConfig.page"
                    :page-sizes="[20, 30, 40]"
                    :page-size="pageConfig.page_size"
                    
                    layout="sizes, prev, pager, next"
                    
                    :total="1000")
</template>
<script>

import Navs from './../../components/nav.vue';
import chinaJson from "./../../assets/chinaChange.json";
import * as echarts from "echarts";
const formCong = { 
    year: new Date().getFullYear().toString(),
    province: '',
    organId: null
}
import {mixin} from './../mixin.js';

export default {
    mixins: [mixin],
    data () {
        return {
            loading: {
                tableLoading: false
            },
            currObj: {
                currentPage: 1,
                onSeniority: 0
            },
            pageConfig: {
                page_size: 20,
                page: 1
            },
            tabList: [],
            tabHeads: [{
                value: "",
                key: "",
                heads: ""
            }],
            result: {
                year: [],
                province: [],
                hospital: [],
                generalObj: {},
                list: []
            },
            form: {
               ...formCong
            }
        };
    },
    computed: {
        filteredHospitals() {
            if (!this.result.province) {
                return {};
            }
            const provinceName = (this.result.province.find((item) => {
                return item.id === this.form.province;
            })|| {}).name;
            return provinceName ? this.result.hospital.filter((item) => {
                return item.province === provinceName;
            }) : this.result.hospital;
        },
    },
    components: {
        Navs
    },
    watch: {
        'result.mapList'(v) {
            const foundItem = v.find(item => item.name === '南海诸岛');
            if (!foundItem) {
                v.push({
                    name: "南海诸岛",
                    value: 0
                })
            }
            v.forEach((k)=>{
                let colorStr= k.name=="南海诸岛"?"#004B43":"white"
                k["itemStyle"]={
                    borderColor: colorStr,
                    // borderWidth: 1,
                };
            });
        },
    },
    methods: {
        getColumnWidth(index) {
            const columnCount = this.tabHeads[this.currObj.onSeniority].heads.length;
            const fixedWidth = ['80px', '', '15%', '15%', '15%', '15%']; // 固定的列宽数组
            if (index < columnCount) {
                return fixedWidth[index];
            } else {
                return ''; // 或者设置默认的列宽
            }
        },
        getProvince() {
            this.axios.get('/ctepapi/admin-api/system/area/tree',
            ).then((resp) => {
                let {errno, errmsg, data} = resp.data;
                if (errno * 1 !== 0) {
                    this.result.province = data.map((n)=>{
                        return {
                            "id": n.id,
                            "name": n.name
                        }
                    });
                }
            });
        },
        getHospital() {
            let params = {
                organType: "hospital"
            }
            this.axios.post('/ctepapi/admin-api/system/organ/list-simple',
                params, 
                {
                    headers: {'Content-Type': 'application/json'}
                }
            ).then((resp) => {
                let {errno, errmsg, data} = resp.data;
                if (errno * 1 !== 0) {
                    this.result.hospital = data;
                }
            });
        },
        
        chinaEcharts() {
            echarts.registerMap("china", chinaJson);
            let myChart = echarts.init(this.$refs.myEcharts);
            let option = {
                backgroundColor: "transparent",
                tooltip: {
                    trigger: "item",
                    backgroundColor: "rgba(0, 0, 0, 0.8)",
                    borderColor: "rgba(0, 0, 0, 0.8)",
                    axisPointer: {
                        type: "line",
                        lineStyle: {
                        },
                    },
                    formatter: (info) => {
                        let {generalObj} = this.result;
                        let {onSeniority} = this.currObj;
                        let txt = `<div class="map-hover-box"><p>${info.name}</p>`;
                        if (generalObj[onSeniority] && generalObj[onSeniority].provinceMap) {
                            let dataObj = (generalObj[onSeniority].provinceMap || {})[info.name]; 
                            let keysArray = (dataObj || []).slice(0, 10);
                            if (keysArray.length > 0) {
                                txt+= '<p>参与机构<span class="sign—colors">'+keysArray.length+'</span>家</p><p class="sign—colors">排名前 10 机构</p>';
                                txt+= '<ul>'
                                keysArray.forEach((n, i) => {
                                    let str = `<li><span>${i + 1}</span>${n.organName}</li>`;
                                    txt += str
                                });
                                txt+= '</ul>';
                            }
                        }
                        let infoHtml = txt+'<div>';
                        return infoHtml;
                    },
                },
                // 1)//加上这个就可以实现多种颜色的功能
                visualMap: {
                    min: 0,
                    max: this.currObj.visualMapMax,
                    text: ["家", ""],
                    calculable: true,
                    seriesIndex: [0], //这个对应的是series的数组下标
                    inRange: {
                        color: ["#C4DAD7", "#004B43"],
                    },
                    left: 0,
                    bottom: -5,
                    orient: 'horizontal',
                    type: 'continuous',
                },
                //series就是地图上的数据（去掉就没有数据了）
                series: [
                    {

                        type: "map",
                        map: "china",
                        geoIndex: 0,
                        zoom: 1.26,
                        // aspectScale: 0.86, //长宽比
                        showLegendSymbol: false, // 存在legend时显示
                        // layoutCenter: ['10%', '10%'],
                        // 如果宽高比大于 1 则宽度为 100，如果小于 1 则高度为 100，保证了不超过 100x100 的区域
                        layoutSize: 90,
                        emphasis: {
                            // disabled: true,
                            itemStyle: {
                                areaColor: "#F0D478",
                            },
                        },
                        roam: false,
                        animation: false,
                        data: this.result.mapList,
                    },
                ],
            };
            myChart.setOption(option);
            window.addEventListener("resize", function () {
                myChart.resize();
            });
        },

        tabListFn(val) {
            this.currObj.onSeniority = val;
            // this.getListData();
        },
        retrieve() {
            this.getListData();
        },
        reset() {
            this.form = {...formCong};
            this.getListData();
        },
        
        handleCurrentChange(page) {
            this.pageConfig.page = page;
            this.getListData();
        },
        handleSizeChange(page) {
            this.pageConfig.page_size = page;
            this.pageConfig.page = 1;
            this.getListData();
        },
        getListData () {
            this.loading.tableLoading = true;
            let params = {
                ...this.form
            };
            this.axios
                .post(
                    "/ctepapi/admin-api/eval/publish-rank/open/list",
                    params,
                    { headers: { "Content-Type": "application/json" } }
                )
                .then((resp) => {
                    let { errno, msg, data } = resp.data;
                    if (errno * 1 !== 0) {
                        this.loading.tableLoading = false;
                        this.tabHeads = [];
                        this.tabList = data.map((n) => {
                            n.heads.unshift('机构名称')
                            n.heads.unshift('位次')
                            this.tabHeads.push({
                                value: n.name,
                                key: n.id,
                                heads: n.heads
                            });
                            return {
                                name: n.name,
                                // val: n.category || "trading",
                                val: (this.tabHeads.length - 1)
                            };
                        });
                        this.tabHeads.length = 4;
                        // let generalObj = {};
                        // data.forEach((n) => {
                        //     generalObj[n.category || "trading"] = n;
                        // });
                        // // this.chinaEcharts();
                        // console.log(Object.keys(generalObj["trading"].organs).length);
                        this.result.generalObj = data;
                    } else {
                        this.$message.error(msg);
                    }
                });
        }
        
    },
    created() {
        // // 假设只有一个值时，默认选中该值
        // if (this.result.year.length === 1) {
        // this.form.year = this.result.year[0].id;
        // }
        // 假设年份范围为 2022 到当前年份
        const currentYear = new Date().getFullYear();
        for (let i = 2023; i <= currentYear; i++) {
            let y = i.toString()
            this.result.year.push(
                {
                    name: `${y}年`,
                    val: y
                }    
            );
        }
        this.result.year.sort((a, b) => b.val - a.val);
    },
    async mounted () {
        // this.form.year = 2023;
        await this._getChinaEcharts();
        this.getProvince();
        this.getHospital();
        this.getListData();
        this.chinaEcharts();
    },
    destroyed () {
    }
};
</script>
<style>
.el-input--small .el-input__inner {
    line-height: 36px !important;
    height: 36px !important;
    font-size: 14px;
}
</style>
<style lang="sass" scoped>
    .list_main_box
        .green-table-theme
            thead
                tr
                    color: #111111
                    th
                        background: #eafcf9
                        text-align: left
                        padding: 12px 20px
                        font-size: 16px
                        font-family: PingFangSC-Medium, PingFang SC
            tbody
                tr
                    td
                        border-bottom: 1px solid #E8E8E8
                        font-size: 16px
                        background: #ffffff
                        color: #333333
                        font-weight: 400
                        padding: 12px 20px

        .map-box
            background: #f6fefd
            display: flex
            padding: 30px 34px
            .l-map
                text-align: center
                height: 480px
                flex: 1
                
                .l
                    width: 100%
                    height: 100%
                    position: relative
                .descr
                    position: absolute
                    bottom: -22px
                    left: 2px
                    font-size: 12px
                    color: #7b7b7b

            .custom

                .particulars
                    overflow: hidden
                    border-radius: 6px
                    background: #eafcf9
                    width: 360px
                    margin-left: 50px
                    height: 420px
                    
                b
                    background: #d2f3ee
                    color: #004B43
                    font-size: 18px
                    padding: 0px 25px
                    height: 46px
                    line-height: 46px
                    display: block
                    span
                         color: #111111
                         font-size: 14px
                .input-box
                    padding: 10px  30px 0
                    .el-select
                        width: 100% !important
                    span
                        display: block
                        font-size: 16px
                        padding-top: 20px
                        padding-bottom: 5px
                        font-family: PingFangSC-Regular, PingFang SC
                        font-weight: 400
                    .select-box
                        width: 100%

                    .filtration
                        padding: 30px 0
                        display: flex
                        li
                            flex: 1
                            text-align: center
                            &:first-child
                                padding-right: 16px
                                .custom-btn
                                    background: #FCFDFF
                                    border: 1px solid #D1E2E0  
                        .custom-btn
                            width: 100%

        .tabs
            border-radius: 6px
            // border-top-right-radius: 6px
            overflow: hidden
            width: 100%
            display: flex
            font-weight: 400
            border-bottom: #fff 1px solid
            li
                cursor: pointer
                flex: 1
                font-family: PingFangSC-Medium, PingFang SC
                text-align: center
                display: inline-block
                padding: 22px 0
                color: #185d56
                font-weight: 500
                font-size: 18px
                background: #d2f3ee
                border-left: #fff 1px solid
                line-height: 0
                &.on
                    color: #FFE6A7 
                    font-size: 20px
                    background: #004B43

        .el-pagination-page
            text-align: center
            padding-bottom: 40px
</style>